import { defineEventHandler, getQuery, createError } from 'h3';
import { getDbConnection } from '../../utils/db.js';
import { requireUser } from '../../utils/auth.js';

export default defineEventHandler(async (event) => {
  try {
    const { userId } = requireUser(event);

    const query = getQuery(event);
    const noteId = query.noteId;

    if (!noteId) {
      throw createError({ statusCode: 400, statusMessage: 'noteId is required' });
    }

    const db = await getDbConnection();
    const note = await db.get(
      'SELECT id, name, content, created_at, updated_at FROM notes WHERE id = ? AND user_id = ?',
      [noteId, userId]
    );

    if (!note) {
      throw createError({ statusCode: 404, statusMessage: 'Note not found' });
    }

    return note;
  } catch (error) {
    console.error('Error fetching note content:', error);
    if (error && error.statusCode) throw error;
    throw createError({ statusCode: 500, statusMessage: 'Failed to fetch note content' });
  }
});
